package com.github.m6d21.sso.common.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;

/**
 *<p>
 *
 *</p>
 *
 * @author liuyang
 * @date 2018/12/26 Wed 11:22:00
 * @since 1.0.0
 */
public class PinyinUtil {

    /**
     * 原字符
     */
    private String source;
    /**
     * 结果格式
     */
    private HanyuPinyinOutputFormat format;
    /**
     * 汉字之间分隔符
     */
    private String separator = "";
    /**
     * 输出结果是否保留非汉字字符, 例如：true: '明Ab3'=>'mingAb3', false: '明Ab3'=>'ming'
     */
    private Boolean retain = true;

    private PinyinUtil(String source) {
        this.source = source;
        this.format = newDefaultFormat();
    }

    public static PinyinUtil on(String chinese) {
        return new PinyinUtil(chinese);
    }

    public PinyinUtil caseType(HanyuPinyinCaseType caseType) {
        if (caseType != null) {
            this.format.setCaseType(caseType);
        }
        return this;
    }

    public PinyinUtil vCharType(HanyuPinyinVCharType vCharType) {
        if (vCharType != null) {
            this.format.setVCharType(vCharType);
        }
        return this;
    }

    public PinyinUtil toneType(HanyuPinyinToneType toneType) {
        if (toneType != null) {
            this.format.setToneType(toneType);
        }
        return this;
    }

    public PinyinUtil separator(String separator) {
        if (separator != null) {
            this.separator = separator;
        }
        return this;
    }

    public PinyinUtil retainNotHanzi(Boolean retain) {
        if (retain != null) {
            this.retain = retain;
        }
        return this;
    }

    public String toPinyin() {
        if (StringUtils.isBlank(source)) {
            return source;
        }

        String result = source;
        try {
            result = PinyinHelper.toHanYuPinyinString(this.source, this.format, this.separator, this.retain);
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }
        return result;
    }

    public static String toPinyin(String chinese) {
        return on(chinese).toPinyin();
    }

    private HanyuPinyinOutputFormat newDefaultFormat() {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        return format;
    }
}
